package qg.fangrui.springboot.config;

import org.apache.catalina.Context;
import org.apache.tomcat.util.http.LegacyCookieProcessor;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

/**
 * Created by zggdczfr on 2017/3/5.
 */
@Configuration
public class CookieConfig {

    @Bean
    public EmbeddedServletContainerCustomizer customizer(){
        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
                tomcat.addContextCustomizers(
                        new TomcatContextCustomizer() {
                            @Override
                            public void customize(Context context) {
                                context.setCookieProcessor(new LegacyCookieProcessor());
                            }
                        });
            }
        };
    }
  //自定义CookieSerializer这样可以解决同级父域名下单点登录不存在跨域问题，nginx测试配置见doc文件夹
  	//相关链接http://blog.didispace.com/spring-session-xjf-3/
  	//http://blog.csdn.net/alaska_bibi/article/details/53126456?locationNum=3&fps=1
	@Bean
	public CookieSerializer cookieSerializer() {
	    DefaultCookieSerializer serializer = new DefaultCookieSerializer();
	    serializer.setCookieName("JSESSIONID");
	    serializer.setCookiePath("/");
	    //域名匹配XX.XX.com
	    serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
	    return serializer;
	}
	
}
